package cn.tedu.knows.portal.controller;

import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
public class SystemController {
    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public String register(
            @Validated RegisterVO registerVO,
            BindingResult result
    ) {
        log.debug("接收到表单信息:{}", registerVO);
        if (result.hasErrors()) {
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        userService.registerStudent(registerVO);
        return "ok";
    }

    @Value("${knows.resource.path}")
    private File resourcePath;

    @Value("${knows.resource.host}")
    private String resourceHost;


    @PostMapping("/upload/file")
    public String upload(MultipartFile imageFile) throws IOException {
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDateTime.now());
        File folder = new File(resourcePath, path);
        folder.mkdirs();
        String filename = imageFile.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + ext;
        File file = new File(folder, name);
        log.debug("文件上传到:{}", file.getAbsolutePath());
        imageFile.transferTo(file);
        String url = resourceHost + "/" + path + "/" + name;
        log.debug("回显图片的路径为:{}", url);
        //返回成功上传文件的静态资源服务器路径
        return url;
    }


}
